/**
 * 日志范围选择，封装了常用今天，7天，30天，全部
 */
import React, { Component } from 'react';
import { DatePicker, Button } from 'antd';
import moment from 'moment';

const RangePicker = DatePicker.RangePicker;
const ButtonGroup = Button.Group;

const styles = {
	rp: {
		width: '204px',
		marginLeft: '1em'
	}
};

function getType(r, value) {
	const days = dayToMoment(value);
	const mat = 'YYYY-MM-DD';
	if (value && value[1] && value[1].format(mat) !== moment().format(mat)) {
		return '';
	}
	return r === days ? 'primary' : '';
}

class DateRange extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			value: props.value || props.defaultValue || []
		};
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.value) this.setState({ value: nextProps.value });
	}

	onButtonClick(days) {
		this.onChange(dayToMoment(days));
	}

	onChange = value => {
		const { onChange } = this.props;
		value = value && value.length > 1 ? [value[0].startOf('day'), value[1].endOf('day')] : value;
		this.setState({ value });
		onChange(value);
	}

	reset = () => {
		this.onButtonClick(0);
	}

	render() {
		const { value } = this.state;
		const { defaultRange, style, ...props } = this.props;

		return (
			<div style={style}>
				<ButtonGroup>
					{defaultRange.map(r => (
						<Button
							key={r}
							type={getType(r, value)}
							onClick={() => this.onButtonClick(r)}
						>
							{r === 1 ? '今天' : r === 0 ? '全部' : `${r}天`}
						</Button>
					))}
				</ButtonGroup>
				<RangePicker style={styles.rp} {...props} value={value} onChange={this.onChange} />
			</div>
		);
	}
}

DateRange.propTypes = {

};

/**
 * 实现天数和moment数组的互转
 * @param {number} val 天数或者是moment数组
 */
export function dayToMoment(val) {
	if (typeof val === 'number') {
		const range = [];
		if (val) {
			range.push(moment().startOf('day').subtract(val - 1, 'days'));
			range.push(moment().endOf('day'));
		}
		return range;
	} else {
		return val.length ? Math.ceil(val[1].diff(val[0]) / 86400000) : 0;
	}
}

/**
 * 天数转为日期字符串
 * @param {number} val
 */
export function dayToDateString(val, format = 'YYYY-MM-DD HH:mm:ss') {
	const tem = dayToMoment(val);
	return tem.length ? [tem[0].format(format), tem[1].format(format)] : tem;
}

export default DateRange;
